
<template>
  <div class="onekit-switch"
       :class="onekitClass"
       :style="onekitStyle"
       :id="onekitId">
    <div class="switch-wrapper"
         :style="{'width':width+'px','height': height+'px','border-radius': (height/2)+'px','background':status ? switchBg : '#e9ebef'}"
         :class="{'close':!status,'disabled':disabled}"
         @click.stop="handleSwitch">
      <div class="slider"
           :style="{'width':(height-2)+'px','height':(height-2)+'px','left':left+'px'}"></div>
    </div>
    <slot></slot>
  </div>
</template>

<script>
/* eslint-disable vue/require-prop-type-constructor */
import weixin_behavior from "../../behaviors/weixin_behavior"
import onekit_behavior from "../../behaviors/onekit_behavior"
import eventBus from '../../api/EventBus'
export default {
  name: "onekit-switch",
  mixins: [weixin_behavior, onekit_behavior],
  data () {
    return {
      status: false,
      left: 1,
      switchBg: "#ED4C67",
    'width': 55,
    'height': 35  
    };
  },
  props: {
    'checked': {
      type: [Boolean, String],
      default: false
    },
    'disabled': {
      type: [Boolean, String],
      default: false
    }
    , 'color': {
      type: [ String],
      default: "#07C160"
    },

  },
  watch: {
    checked (data) {
      this.status = data
      this.changeStatus();
    },
    color (data) {
      if (data) {
        if (data.indexOf("#") == -1) {
          this.switchBg = "#ED4C67"
        } else {
          this.switchBg = data;
        }
      }
    }
  },
  methods: {
    changeStatus () {
      if (this.status) {
        this.left = this.width - (this.height - 1);
      } else {
        this.left = 1
      }
    },
    handleSwitch (e) {
      if (this.disabled) {
        return;
      }
      this.status=! this.status
      this.changeStatus()

      const res = {
        currentTarget: {
          dataset: {},
          id: '',
          offsetLeft: e.clientX,
          offsetTop: e.clientY
        },
        detail: {
          value: this.status
        },
        mark: {},
        mut: false,
        target: {
          dataset: {},
          id: '',
          offsetLeft: e.clientX,
          offsetTop: e.clientY
        },
        timeStamp: parseInt(e.timeStamp),
        type: 'change',
        _userTap: true
      }
      this.$emit("Change", res)
      eventBus.$emit('onekit-switch-submit', this.status)
    }
  },
  mounted () {
      this.status = this.checked;
    this.changeStatus()
    if (this.switchBg != this.color) {
      this.switchBg = this.color
    }
    eventBus.$on('onekit-foem-item-reset', () => {
      if (!this.checked) this.status = false
      eventBus.$emit('onekit-switch-submit', this.status)
    })
  },
}
</script>

<style>
</style>
